package com.xin.libhtmlcontent.web.lib;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.xin.libhtmlcontent.R;


/*WebView 功能封装*/
public class WebViewUtils {
    WebView webView;
    Activity context;

    public WebViewUtils(Activity context) {
        this.context = context;
    }

    public void initWebView(WebView webView) {
        this.webView = webView;
        WebSettings setting = webView.getSettings();
        setting.setJavaScriptEnabled(true);
        setting.setLoadWithOverviewMode(true);
        setting.setBuiltInZoomControls(false);
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setDatabaseEnabled(true);
        setting.setUseWideViewPort(true); /*加载手机版的 */
        setting.setSupportZoom(true);
        int backColor = Color.WHITE;
        webView.setBackgroundColor(backColor);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
            webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
    }

    public void loadJs(String js) {
        String jsCommand = "javascript:" + js;
        log("loadJs() called with: jsCommand = [" + jsCommand + "]");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(jsCommand, null);
        } else {
            webView.loadUrl(jsCommand);
        }

    }

    public void initWebClient() {
        webView.setWebChromeClient(new MyWebChromeClient(context));
        webView.setWebViewClient(new MyWebViewClient());
    }

    /**
     * Created by xin on 2017/9/28.
     * 视频全屏
     * http://blog.csdn.net/u014513456/article/details/54381361
     * 1.activity android:configChanges="keyboardHidden|orientation|screenSize"
     * 2.js也要设置
     */

    public class VideoFullScreenWebChromeClient extends WebChromeClient {
        private View mCustomView;
        Activity context;
        private CustomViewCallback mCustomViewCallback;
        private int mOriginalOrientation;
        private int mOriginalSystemUiVisibility;

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (this == null) {
                return null;
            }
            //这个地方是加载h5的视频列表 默认图   点击前的视频图
            return BitmapFactory.decodeResource(context.getApplicationContext().getResources(),
                    R.drawable.default_video);
        }

        public VideoFullScreenWebChromeClient(Activity context) {
            this.context = context;
        }

        @SuppressLint("SourceLockedOrientationActivity")
        @Override
        public void onShowCustomView(View view,
                                     CustomViewCallback callback) {
            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                onHideCustomView();
                return;
            }

            // 1. Stash the current state
            mCustomView = view;
            mOriginalSystemUiVisibility = context.getWindow().getDecorView().getSystemUiVisibility();
            mOriginalOrientation = context.getRequestedOrientation();
            // 2. Stash the custom view callback
            mCustomViewCallback = callback;
            // 3. Add the custom view to the view hierarchy
            FrameLayout decor = (FrameLayout) context.getWindow().getDecorView();
            decor.addView(mCustomView, new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));

            (mCustomView).setBackgroundColor(Color.BLACK);

            // 4. Change the state of the window
            context.getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE);
            context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        @Override
        public void onHideCustomView() {
            // 1. Remove the custom view
            FrameLayout decor = (FrameLayout) context.getWindow().getDecorView();
            decor.removeView(mCustomView);
            mCustomView = null;

            // 2. Restore the state to it's original form
            context.getWindow().getDecorView()
                    .setSystemUiVisibility(mOriginalSystemUiVisibility);
            context.setRequestedOrientation(mOriginalOrientation);

            // 3. Call the custom view callback
            if (mCustomViewCallback != null) {
                mCustomViewCallback.onCustomViewHidden();
                mCustomViewCallback = null;
            }

        }
    }

    class MyWebChromeClient extends VideoFullScreenWebChromeClient {
        public MyWebChromeClient(Activity context) {
            super(context);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            log("onReceivedTitle() called with: " + "view = [" + view + "], title = [" + title + "]");
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log("onConsoleMessage() called with: " + "consoleMessage = [" + consoleMessage.message() + "]");
            return false;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            log("onProgressChanged() called with: " + "view = [" + view + "], newProgress = [" + newProgress + "]");
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            log("onShowCustomView() called with: view = [" + view + "], callback = [" + callback + "]");
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
            log("onHideCustomView() called");
        }
    }

    class MyWebViewClient extends WebViewClient {


        public MyWebViewClient() {
            log("MyWebViewClient() called");
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            super.shouldOverrideUrlLoading(view, request);
            log("shouldOverrideUrlLoading() called with: " + "view = [" + view + "], request = [" + request + "]");
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            log("onPageStarted() called with: " + "view = [" + view + "], url = [" + url + "], favicon = [" + favicon + "]");
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            log("onReceivedError:" + error);

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            log("onReceivedSslError() called with: " + "view = [" + view + "], handler = [" + handler + "], error = [" + error + "]");
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
            log("onLoadResource() called with: " + "view = [" + view + "], url = [" + url + "]");
        }

        @Override
        public void onReceivedHttpError(
                WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            log("onReceivedHttpError() called with: " + "view = [" + view + "], request = [" + request + "], errorResponse = [" + errorResponse + "]");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            log("onPageFinished() called with: " + "view = [" + view + "], url = [" + url + "]");
            WebViewUtils.this.onPageFinished(view, url);
        }

    }

    protected void onPageFinished(WebView view, String url) {

    }

    private void log(String s) {

    }
}
